using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;

namespace SmartLink.Infrastructure
{
    public class IOHelper
    {
        public static void CopyFile(string fileFullPath, string destination, bool isDeleteSourceFile = false, string fileName = "")
        {
            if (string.IsNullOrWhiteSpace(fileFullPath))
            {
                throw new ArgumentNullException("fileFullPath", "源文件全路径不能为空");
            }
            if (!File.Exists(fileFullPath))
            {
                throw new FileNotFoundException("找不到源文件", fileFullPath);
            }
            if (!Directory.Exists(destination))
            {
                throw new DirectoryNotFoundException("找不到目标目录 " + destination);
            }
            try
            {
                fileName = string.IsNullOrWhiteSpace(fileName) ? Path.GetFileName(fileFullPath) : fileName;
                File.Copy(fileFullPath, Path.Combine(destination, fileName), true);
                if (isDeleteSourceFile)
                {
                    File.Delete(fileFullPath);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static long GetDirectoryLength(string dirPath)
        {
            if (!Directory.Exists(dirPath))
            {
                return 0L;
            }
            long num = 0L;
            DirectoryInfo info = new DirectoryInfo(dirPath);
            foreach (FileInfo info2 in info.GetFiles())
            {
                num += info2.Length;
            }
            DirectoryInfo[] directories = info.GetDirectories();
            if (directories.Length > 0)
            {
                for (int i = 0; i < directories.Length; i++)
                {
                    num += GetDirectoryLength(directories[i].FullName);
                }
            }
            return num;
        }

        public static string GetMapPath(string path)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(path);
            }
            string applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (!string.IsNullOrWhiteSpace(path))
            {
                path = path.Replace("/", @"\");
                if (!path.StartsWith(@"\"))
                {
                    path = @"\" + path;
                }
                path = path.Substring(path.IndexOf('\\') + (applicationBase.EndsWith(@"\") ? 1 : 0));
            }
            return (applicationBase + path);
        }
    }
}
